'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import { 
  CheckCircleIcon, 
  CheckIcon, 
  PencilSquareIcon, 
  TrashIcon,
  ArrowLeftIcon,
  ChatBubbleLeftRightIcon,
} from '@heroicons/react/24/outline'
import Button from '@/components/ui/Button'
import { formatDate } from '@/lib/utils'

interface User {
  id: string
  name: string
  role: string
}

interface Answer {
  id: string
  content: string
  isAccepted: boolean
  createdAt: string
  author: User
}

interface Question {
  id: string
  title: string
  content: string
  isSolved: boolean
  viewCount: number
  createdAt: string
  author: User
  experiment: {
    id: string
    title: string
  }
  answers: Answer[]
}

export default function QuestionDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { data: session, status } = useSession()
  const [question, setQuestion] = useState<Question | null>(null)
  const [answerContent, setAnswerContent] = useState('')
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  const questionId = params.id as string

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/login')
      return
    }

    if (status === 'loading') return

    fetchQuestion()
  }, [status, questionId])

  const fetchQuestion = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/forum/questions/${questionId}`)
      
      if (!response.ok) {
        throw new Error('获取问题详情失败')
      }
      
      const data = await response.json()
      setQuestion(data.question)
    } catch (err: any) {
      setError(err.message || '获取问题详情失败')
    } finally {
      setLoading(false)
    }
  }

  const handleSubmitAnswer = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!answerContent.trim()) {
      setError('回答内容不能为空')
      return
    }
    
    try {
      setSubmitting(true)
      setError('')
      
      const response = await fetch(`/api/forum/questions/${questionId}/answers`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: answerContent,
        }),
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '发布回答失败')
      }
      
      const data = await response.json()
      
      // 重新获取问题详情，包含新回答
      await fetchQuestion()
      
      // 清空表单
      setAnswerContent('')
    } catch (err: any) {
      setError(err.message || '发布回答失败')
    } finally {
      setSubmitting(false)
    }
  }

  const handleAcceptAnswer = async (answerId: string) => {
    try {
      const response = await fetch(`/api/forum/answers/${answerId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          isAccepted: true,
        }),
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '接受回答失败')
      }
      
      // 重新获取问题详情
      await fetchQuestion()
    } catch (err: any) {
      setError(err.message || '接受回答失败')
    }
  }

  const handleDeleteAnswer = async (answerId: string) => {
    if (!confirm('确定要删除这个回答吗？')) {
      return
    }
    
    try {
      const response = await fetch(`/api/forum/answers/${answerId}`, {
        method: 'DELETE',
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '删除回答失败')
      }
      
      // 重新获取问题详情
      await fetchQuestion()
    } catch (err: any) {
      setError(err.message || '删除回答失败')
    }
  }

  const handleDeleteQuestion = async () => {
    if (!confirm('确定要删除这个问题吗？所有相关回答也会被删除。')) {
      return
    }
    
    try {
      const response = await fetch(`/api/forum/questions/${questionId}`, {
        method: 'DELETE',
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '删除问题失败')
      }
      
      // 删除成功后跳转回论坛首页
      router.push(question?.experiment?.id 
        ? `/forum?experimentId=${question.experiment.id}` 
        : '/forum'
      )
    } catch (err: any) {
      setError(err.message || '删除问题失败')
    }
  }

  const isQuestionAuthor = question?.author?.id === session?.user?.id
  const isTeacherOrAdmin = session?.user?.role === 'TEACHER' || session?.user?.role === 'ADMIN'
  const canManageQuestion = isQuestionAuthor || isTeacherOrAdmin

  if (loading) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">加载中...</div>
        </div>
      </div>
    )
  }

  if (error && !question) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-red-50 p-4 rounded-md">
            <div className="text-sm text-red-700">{error}</div>
          </div>
        </div>
      </div>
    )
  }

  if (!question) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">问题不存在或无权访问</div>
        </div>
      </div>
    )
  }

  return (
    <div className="py-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="mb-6">
          <Link
            href={question.experiment?.id 
              ? `/forum?experimentId=${question.experiment.id}` 
              : '/forum'
            }
            className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700"
          >
            <ArrowLeftIcon className="h-4 w-4 mr-1" />
            返回论坛
          </Link>
        </div>

        {error && (
          <div className="mb-6 rounded-md bg-red-50 p-4">
            <div className="text-sm text-red-700">{error}</div>
          </div>
        )}

        <div className="bg-white shadow sm:rounded-lg overflow-hidden mb-6">
          <div className="px-4 py-5 sm:px-6 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-semibold text-gray-900">
                {question.isSolved && (
                  <CheckCircleIcon className="inline-block h-6 w-6 text-green-500 mr-2" />
                )}
                {question.title}
              </h2>
              {canManageQuestion && (
                <div className="flex space-x-2">
                  <Link
                    href={`/forum/${question.id}/edit`}
                    className="inline-flex items-center p-1.5 border border-transparent text-sm font-medium rounded text-primary-700 hover:bg-primary-100"
                  >
                    <PencilSquareIcon className="h-5 w-5" />
                  </Link>
                  <button
                    onClick={handleDeleteQuestion}
                    className="inline-flex items-center p-1.5 border border-transparent text-sm font-medium rounded text-red-700 hover:bg-red-100"
                  >
                    <TrashIcon className="h-5 w-5" />
                  </button>
                </div>
              )}
            </div>
            <div className="mt-1 flex items-center text-sm text-gray-500">
              <span className="mr-3">
                {question.author.name || '匿名用户'}
                <span className="ml-1 text-xs text-gray-400">
                  ({question.author.role === 'TEACHER'
                    ? '教师'
                    : question.author.role === 'ADMIN'
                    ? '管理员'
                    : '学生'})
                </span>
              </span>
              <span className="mr-3">
                发布于 {formatDate(new Date(question.createdAt))}
              </span>
              <span className="mr-3">
                实验: {question.experiment.title}
              </span>
              <span>
                浏览: {question.viewCount}
              </span>
            </div>
          </div>
          <div className="px-4 py-5 sm:p-6">
            <div className="prose max-w-none">
              <p className="whitespace-pre-line">{question.content}</p>
            </div>
          </div>
        </div>

        <div className="mb-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            {question.answers.length > 0 
              ? `${question.answers.length} 个回答`
              : '还没有回答'
            }
          </h3>

          {question.answers.length === 0 ? (
            <div className="bg-white shadow sm:rounded-lg p-6 text-center">
              <ChatBubbleLeftRightIcon className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">还没有回答</h3>
              <p className="mt-1 text-sm text-gray-500">
                成为第一个回答这个问题的人
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {question.answers.map((answer) => (
                <div
                  key={answer.id}
                  className={`bg-white shadow sm:rounded-lg overflow-hidden ${
                    answer.isAccepted ? 'border-2 border-green-500' : ''
                  }`}
                >
                  <div className="px-4 py-3 sm:px-6 bg-gray-50 flex justify-between items-center">
                    <div className="flex items-center text-sm text-gray-500">
                      <span className="mr-3">
                        {answer.author.name || '匿名用户'}
                        <span className="ml-1 text-xs text-gray-400">
                          ({answer.author.role === 'TEACHER'
                            ? '教师'
                            : answer.author.role === 'ADMIN'
                            ? '管理员'
                            : '学生'})
                        </span>
                      </span>
                      <span>
                        回答于 {formatDate(new Date(answer.createdAt))}
                      </span>
                      {answer.isAccepted && (
                        <span className="ml-3 inline-flex items-center text-green-700">
                          <CheckIcon className="h-4 w-4 mr-1" />
                          已采纳
                        </span>
                      )}
                    </div>
                    <div className="flex space-x-2">
                      {(isQuestionAuthor || isTeacherOrAdmin) && !answer.isAccepted && (
                        <button
                          onClick={() => handleAcceptAnswer(answer.id)}
                          className="inline-flex items-center p-1.5 border border-transparent text-sm font-medium rounded text-green-700 hover:bg-green-100"
                          title="采纳回答"
                        >
                          <CheckIcon className="h-5 w-5" />
                        </button>
                      )}
                      {(answer.author.id === session?.user?.id || isTeacherOrAdmin) && (
                        <button
                          onClick={() => handleDeleteAnswer(answer.id)}
                          className="inline-flex items-center p-1.5 border border-transparent text-sm font-medium rounded text-red-700 hover:bg-red-100"
                          title="删除回答"
                        >
                          <TrashIcon className="h-5 w-5" />
                        </button>
                      )}
                    </div>
                  </div>
                  <div className="px-4 py-5 sm:p-6">
                    <div className="prose max-w-none">
                      <p className="whitespace-pre-line">{answer.content}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="bg-white shadow sm:rounded-lg overflow-hidden">
          <div className="px-4 py-5 sm:p-6">
            <h3 className="text-lg font-medium text-gray-900 mb-4">
              你的回答
            </h3>
            <form onSubmit={handleSubmitAnswer}>
              <div className="mb-4">
                <textarea
                  rows={6}
                  className="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  placeholder="请输入你的回答..."
                  value={answerContent}
                  onChange={(e) => setAnswerContent(e.target.value)}
                  required
                />
              </div>
              <div className="flex justify-end">
                <Button
                  type="submit"
                  disabled={submitting}
                >
                  {submitting ? '提交中...' : '提交回答'}
                </Button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
} 